/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.user.client.impl;

import org.jb.user.client.Login;
import org.jb.user.client.LoginListener;
import org.jb.user.client.LoginPanel;
import org.jb.user.client.UserProvider;
import org.jb.user.client.LoginPanel.LoginPanelListener;
import org.jb.user.client.rpc.UserServiceAsync;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * @author jeremie
 *
 */
@Singleton
public class LoginImpl implements Login, LoginPanelListener {

	/* (non-Javadoc)
	 * @see org.jb.coinche.client.user.Login#login()
	 */
	@Override
	public void login() {
		userService.autologin(new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(String result) {
				logged( result );
			}
			
			@Override
			public void onFailure(Throwable caught) {
				loginPanel.setListener(LoginImpl.this);
				loginPanel.show();
			}
		});
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.user.LoginPanel.LoginPanelListener#onLogin(java.lang.String, java.lang.String)
	 */
	@Override
	public void onLogin(String user, String password) {
		userService.connect(user, password , new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				loginPanel.failed();
			}

			@Override
			public void onSuccess(String result) {
				loginPanel.hide();
				logged( result );
			}
		} );	
	}
	
	/*
	 * 
	 */
	private void logged( String result ) {
		userProvider.setUser( result );
		
		loginListener.logged();
	}
	
	@Inject
	private UserServiceAsync userService;
	
	@Inject
	private LoginPanel loginPanel;
	
	@Inject
	private UserProvider userProvider;
	
	@Inject
	private LoginListener loginListener;

	
}
